import {Message} from "@arco-design/web-vue";
import {useMapStore} from "./index";
import {clearSearchMarkers, renderSearchMarkers} from "./map";

// 搜索当前地图区域的地址
export const searchInCurrentArea = () => {
    const store = useMapStore();

    if (!store.map || !store.searchKeyword) return;

    store.isSearching = true;
    const bounds = store.map.getBounds();
    const local = new window.BMapGL.LocalSearch(store.map, {
        onSearchComplete: (results: any) => {
            store.searchResults = [];
            clearSearchMarkers();

            if (local.getStatus() === window.BMAP_STATUS_SUCCESS) {
                const allResults = [];
                for (let i = 0; i < results.getCurrentNumPois(); i++) {
                    const poi = results.getPoi(i);
                    const uid = poi.uid || `${poi.point.lng}_${poi.point.lat}`;

                    // 检查该地址是否已经添加到地址列表中
                    const exists = store.addressList.find(item => item.uid === uid);
                    if (!exists) {
                        allResults.push({
                            title: poi.title,
                            address: poi.address,
                            point: poi.point,
                            uid: uid,
                            index: allResults.length,
                        });
                    }
                }
                store.searchResults = allResults;
                // 在地图上显示搜索结果标记
                renderSearchMarkers();
            }
            store.isSearching = false;
        },
    });

    local.searchInBounds(store.searchKeyword, bounds);
};

// 执行搜索
export const handleSearch = () => {
    const store = useMapStore();

    if (!store.searchKeyword.trim()) {
        Message.warning("请输入搜索关键词");
        return;
    }
    store.selectedSearchResultIndex = -1;
    searchInCurrentArea();
};
